package com.yanq.liancar.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBBean;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.MyCar;
import com.yanq.liancar.bean.MyOBD;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.net.util.ProgressSubscriber;
import com.yanq.liancar.util.DensityUtil;
import com.yanq.liancar.util.Utils;
import com.yanq.liancar.view.popupwindow.OnPositiveListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.OptionPicker;

public class BindOBDActivity extends BaseToolbarActivity {


    @BindView(R.id.bindOBD_bind)
    TextView bindOBDBind;
    @BindView(R.id.bind_car_chepaihao)
    TextView bind_car_chepaihao;
    @BindView(R.id.rl_carnum)
    RelativeLayout rlCarnum;
    @BindView(R.id.bindOBD_et)
    EditText bindOBDEt;
    @BindView(R.id.bind_obd_root)
    LinearLayout bindObdRoot;
    private String carId = "";
    private String OBDId = "";
    private List<MyCar.DataBean> mMyCars = new ArrayList<>();
    private int OBDPos = 0;
    private List<MyOBD.DateBean> mMyOBDs = new ArrayList<>();
    private int obdId = -1;

    public static void start(Context context, int OBDId, String OBDNum, String OBDCar) {
        Intent intent = new Intent(context, BindOBDActivity.class);
        intent.putExtra("OBDId", OBDId);
        intent.putExtra("OBDNum", OBDNum);
        intent.putExtra("OBDCar", OBDCar);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_obd);
        ButterKnife.bind(this);
        Utils.setStatusBar(this, true, false);
        mTvTitle.setText("绑定ODB");
        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setText("解绑");
        mTvRight.setTextColor(getResources().getColor(R.color.main_color));
        mTvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(carId)) {
                    showUnbindDialog();
                }
            }
        });
        mTvRight.setVisibility(View.GONE);
        //        Bundle bundle;
        //        bundle = getIntent().getExtras();
        //        if (bundle != null) {
        //            OBDPos = bundle.getInt("OBDPos");
        //            //initOkGoOBD();
        //        }

        obdId = getIntent().getIntExtra("OBDId", -1);
        String obdNum = getIntent().getStringExtra("OBDNum");
        String OBDCar = getIntent().getStringExtra("OBDCar");
        if (obdId != -1) {
            bindOBDBind.setText("解绑");
            bindOBDEt.setText(obdNum != null ? obdNum : "");
            bind_car_chepaihao.setText(OBDCar != null ? OBDCar : "");
        } else {
            bindOBDBind.setText("绑定");
        }
    }


    /*获取OBD*/
    private void initOkGoOBD() {
        OkGo.<String>post("http://test19.value19.com" + "/Obd.php/Index/obdvehicle")
                .tag(this)
                .params("id", RxSPTool.getString(this, "UserId"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        MyOBD bean = gson.fromJson(response.body(), MyOBD.class);
                        mMyOBDs.addAll(bean.getDate());
                        if (mMyOBDs.isEmpty() || mMyOBDs.size() == 0) {

                        } else {
                            carId = mMyOBDs.get(OBDPos).getChid();
                            bind_car_chepaihao.setText(mMyOBDs.get(OBDPos).getChepai() + "");
                        }
                    }
                });
    }

    private void initOptionPicker(String[] mStr) {
        final OptionPicker picker = new OptionPicker(BindOBDActivity.this, mStr);
        picker.setSubmitText("确定");
        picker.setCancelText("取消");
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int position, String option) {
                //                        showToast(option);
                bind_car_chepaihao.setText(option);
                //carId = mMyCars.get(position).getChid();
                picker.dismiss();
            }
        });
        picker.show();
    }

    /*获取CARLIST*/
    private void initOkGoCar() {
        OkGo.<String>post("http://test19.value19.com" + "/Obd.php/Index/vehicle")
                .tag(this)
                .params("id", RxSPTool.getString(this, "UserId"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        mMyCars = new ArrayList<>();
                        Gson gson = new Gson();
                        MyCar bean = gson.fromJson(response.body(), MyCar.class);
                        if (bean.isIsSuccess()) {
                            mMyCars = bean.getData();
                            if (mMyCars.isEmpty() || mMyCars.size() == 0) {
                                RxToast.warning("请先绑定车辆");
                                RxSPTool.putString(BindOBDActivity.this, "SelectAddressTitle", "鲁A");
                                Intent intent = new Intent(BindOBDActivity.this, BindCarActivity.class);
                                startActivity(intent);
                            } else {
                                List<String> stringList = new ArrayList<>();
                                for (int i = 0; i < mMyCars.size(); i++) {
                                    //stringList.add(mMyCars.get(i).getChepai());
                                }
                                String[] stringArray = stringList.toArray(new String[stringList.size()]);
                                initOptionPicker(stringArray);
                            }
                        }
                    }
                });
    }


    private void initOkGo() {
        OkGo.<String>post("http://test19.value19.com" + "/Obd.php/Index/obdbinding")
                .tag(this)
                .params("id", carId)
                .params("equipment", bindOBDEt.getText().toString().trim())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBBean bean = gson.fromJson(response.body(), BaseBBean.class);
                        if (bean.isStatus()) {
                            RxToast.success("绑定成功");
                            carId = "";
                            finish();
                        } else {
                            RxToast.error("绑定失败");
                        }
                    }
                });
    }

    private void initUnBind() {
        OkGo.<String>post("http://test19.value19.com" + "/Obd.php/Index/obddel")
                .tag(this)
                .params("id", carId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBBean bean = gson.fromJson(response.body(), BaseBBean.class);
                        if (bean.isStatus()) {
                            RxToast.success("解绑成功");
                            carId = "";
                            finish();
                        } else {
                            RxToast.error("解绑失败");
                        }
                    }
                });
    }

    private void showUnbindDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_unbind, null);
        final Dialog dialog = new Dialog(this, R.style.AlertDialog);
        dialog.setContentView(view);
        TextView positiveButton = (TextView) view.findViewById(R.id.positiveButton);
        TextView negativeButton = (TextView) view.findViewById(R.id.negativeButton);
        TextView title = (TextView) view.findViewById(R.id.dialog_title);
        title.setText("您确定要解除绑定OBD吗");
        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//确定
                dialog.dismiss();
                initUnBind();

            }
        });
        negativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                return;
            }
        });
        dialog.show();
    }

    private void showSelectCarDialog() {
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_selectcar, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels - DensityUtil.dp2px(this, 80f);
        contentView.setLayoutParams(params);
        TextView positiveButton = (TextView) contentView.findViewById(R.id.positiveButton);
        TextView negativeButton = (TextView) contentView.findViewById(R.id.negativeButton);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();

            }
        });
        negativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
                return;
            }
        });
        bottomDialog.show();
    }

    @OnClick({R.id.rl_carnum, R.id.bindOBD_bind, R.id.scan_obd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_carnum:
                //showSelectCarDialog();
                //initOkGoCar();
                PopWinCar popWinCar = new PopWinCar(mContext);
                popWinCar.showAtLocation(bindObdRoot, Gravity.BOTTOM, 0, 0);
                popWinCar.setOnPositiveListener(new OnPositiveListener() {
                    @Override
                    public void onPositive(String value) {
                        bind_car_chepaihao.setText(value);
                    }
                });
                break;
            case R.id.bindOBD_bind:

                if (obdId != -1) {
                    bindOBDBind.setText("解绑");
                    unBindOBD();
                } else {
                    String obdNum = bindOBDEt.getText().toString().trim();
                    String chepaihao = bind_car_chepaihao.getText().toString().trim();
                    if (!TextUtils.isEmpty(obdNum) && !TextUtils.isEmpty(chepaihao)) {
                        //                        initOkGo();
                        bindOBD(obdNum, chepaihao);
                    } else {
                        RxToast.showToast("请填写完整");
                    }
                }
                break;
            case R.id.scan_obd:
                Intent intent=new Intent(mContext, ScanerCodeActivity.class);
                intent.putExtra("where","BindOBDActivity");
                startActivityForResult(intent,001);
                break;
        }
    }

    private void unBindOBD() {
        mHttpUtil.unBindObd(new ProgressSubscriber<BaseBean>(mContext) {
            @Override
            public void next(BaseBean baseBean) {
                if (baseBean.isIsSuccess()) {
                    RxToast.success("解绑成功");
                    finish();
                } else {
                    RxToast.error("解绑失败");
                }
            }
        }, UserBean.getcToken(mContext), String.valueOf(obdId));
    }

    private void bindOBD(String obdNum, String chepaihao) {
        mHttpUtil.bindObd(new ProgressSubscriber<BaseBean>(mContext) {
            @Override
            public void next(BaseBean baseBean) {
                if (baseBean.isIsSuccess()) {
                    RxToast.success("绑定成功");
                    finish();
                } else {
                    RxToast.error("绑定失败");
                }
            }
        }, UserBean.getcToken(mContext), chepaihao, obdNum);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
//        if (result != null) {
//            if (result.getContents() == null) {
//                ToastUtil.show(mContext, "扫码取消！");
//            } else {
//                bindOBDEt.setText(result.getContents());
//            }
//        } else {
//            super.onActivityResult(requestCode, resultCode, data);
//        }

        if (resultCode==RESULT_OK){
            if (requestCode==001){
                bindOBDEt.setText(data.getStringExtra("code"));
            }
        }
    }

}
